package com.autumn.cloud.demo.consumer.services.impl;

import com.autumn.cloud.demo.common.constants.DemoServiceProviderUrlConstants;
import com.autumn.cloud.demo.common.model.UserInfo;
import com.autumn.cloud.demo.common.service.ProviderCommonService;
import com.autumn.cloud.demo.consumer.configure.ClientAutoConfigure;
import com.autumn.cloud.demo.consumer.services.UserInfoService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * <p>
 * </p>
 *
 * @description TODO
 * @author: 老码农
 * @create: 2020-12-11 15:56
 **/
@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private final ProviderCommonService providerCommonService;
    @Resource(name = ClientAutoConfigure.BEAN_REST_BALANCED_TEMPLATE, description = "负载均衡")
    private RestTemplate restBalancedTemplate;

    public UserInfoServiceImpl(ProviderCommonService providerCommonService) {
        this.providerCommonService = providerCommonService;
    }

    @Override
    public UserInfo userInfo() {
        // http://autumn-cloud-demo-provider/user/info
        String url = this.providerCommonService.getDemoServiceUrl() + DemoServiceProviderUrlConstants.USER_INFO_URL;
        UserInfo userInfo = this.restBalancedTemplate.getForObject(url, UserInfo.class);
        return this.restBalancedTemplate.getForObject(url, UserInfo.class);
    }

    @HystrixCommand(fallbackMethod = "userInfoHystrix")
    private UserInfo userInfoHystrix() {
        UserInfo userInfo = new UserInfo();
        userInfo.setMsg("Ribbon 熔断，服务器已断开，暂时无法访问");
        return userInfo;
    }
}
